package com.mxpio.erp.hr.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.mxpio.erp.common.enums.HrEnums;
import com.mxpio.erp.common.hr.entity.AttendanceCalendar;
import com.mxpio.erp.common.hr.service.AttendanceCalendarService;
import com.mxpio.erp.common.util.HolidayUtil;
import com.mxpio.erp.common.vo.HolidayVo;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class AttendanceCalendarServiceImpl extends BaseServiceImpl<AttendanceCalendar> implements AttendanceCalendarService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> sync(String year) {
        try {
            DateUtil.parse(year, "yyyy");
        } catch (Exception e) {
            // 若解析过程中出现异常，说明输入不是有效的年份
            return Result.error("输入的年份格式不正确-》"+year);
        }

        try {
            ArrayList<HolidayVo> allHolidayByYear = HolidayUtil.getAllHolidayByYear(year);
            if (allHolidayByYear.size() > 0) {
                JpaUtil.lind(AttendanceCalendar.class).equal("year", year).delete();//先删除历史数据
                List<AttendanceCalendar> attendanceCalendarList = new ArrayList<>();
                for (HolidayVo holidayVo : allHolidayByYear) {
                    String date = holidayVo.getData();//格式2025-01-02
                    DateTime parse = DateUtil.parse(date, "yyyy-MM-dd");
                    AttendanceCalendar attendanceCalendar = new AttendanceCalendar();
                    attendanceCalendar.setDate(date);
                    attendanceCalendar.setYear(parse.year()+"");
                    attendanceCalendar.setMonth(parse.toString("yyyy-MM"));
                    attendanceCalendar.setDateType(holidayVo.getStatus());
                    if (holidayVo.getStatus().equals(HrEnums.AttendanceCalendarDataType.TURNOVER.getCode())) {//状态：0工作日/1周末/2法定节假日/3节假日调休补班
                        attendanceCalendar.setDateType(HrEnums.AttendanceCalendarDataType.WORK.getCode());//3节假日调休补班 归为0工作日类型
                    }
                    attendanceCalendarList.add(attendanceCalendar);
                }
                if (attendanceCalendarList.size() > 0) {
                    JpaUtil.save(attendanceCalendarList);
                }
            }
        } catch (Exception e) {
            return Result.error("调用日历同步接口失败："+e.getMessage());
        }
        return Result.OK("工作日历同步成功！",null);
    }

    @Override
    @Transactional
    public Integer getWorkDays(String yearMonth) {//获取月份对应的工作天数
        return JpaUtil.linq(AttendanceCalendar.class).equal("dateType", HrEnums.AttendanceCalendarDataType.WORK.getCode()).equal("month", yearMonth).count().intValue();
    }
}
